package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/google/go-tika/tika"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("syntax: ./pdf2html filename")
		return
	}
	filename := os.Args[1]
	filename, err := filepath.Abs(filename)
	if err != nil {
		fmt.Println(err)
		return
	}

	content, err := readPdf(filename) // Read local pdf file
	if err != nil {
		fmt.Println(err)
		return
	}
	content = strings.Replace(content, "</body>", script()+"</body>", 1)

	dir, name := filepath.Split(filename)
	name = strings.Replace(name, filepath.Ext(filename), ".html", 1)
	outfilename := filepath.Join(dir, name)
	err = os.WriteFile(outfilename, []byte(content), os.ModeAppend|os.ModePerm)
	if err != nil {
		fmt.Println(err)
		return
	}
}

func readPdf(path string) (string, error) {
	f, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer f.Close()

	client := tika.NewClient(nil, "http://127.0.0.1:9998")
	return client.Parse(context.TODO(), f)
}

func script() string {
	return `
<script>
	// 创建自定义的上下文菜单  
	var customMenu = document.createElement('div');
	customMenu.style.position = 'fixed';
	customMenu.style.zIndex = '1000';
	customMenu.style.padding = '5px';
	customMenu.style.backgroundColor = 'lightgray';
	customMenu.style.border = '1px solid gray';

	// 添加删除选项  
	var deleteOption = document.createElement('button');
	deleteOption.textContent = '删除选择文本';
	deleteOption.style.display = "block"
	deleteOption.addEventListener('click', function () {
		var selection = window.getSelection();
		var range = selection.getRangeAt(0);
		range.deleteContents();
	});
	customMenu.appendChild(deleteOption);

	// 添加合并段落选项
	var mergeOption = document.createElement('button');
	mergeOption.textContent = '合并段落';
	mergeOption.style.display = "block"
	mergeOption.addEventListener('click', function () {
		mergeParagraphs()
		// var selection = window.getSelection();
		// var range = selection.getRangeAt(0);
		// range.deleteContents();
	});
	customMenu.appendChild(mergeOption);

	// 将自定义菜单添加到文档中  
	document.body.appendChild(customMenu);
	customMenu.style.display = 'none'


	// 弹出菜单响应事件
	document.addEventListener('contextmenu', function (event) {
		// 检查是否有选择的文本  
		var selection = window.getSelection();
		if (selection.rangeCount > 0 && selection.toString() != "") {
			event.preventDefault(); // 阻止默认的右键菜单显示  

			customMenu.style.left = event.clientX + 'px';
			customMenu.style.top = event.clientY + 'px';
			customMenu.style.display = "block"
		}
	});
	// 监听body上的点击事件，用于关闭上下文菜单
	document.addEventListener('click', function () {
		customMenu.style.display = 'none'
	})

	function mergeParagraphs() {
		// 获取用户选择的文本范围
		const selection = window.getSelection();
		if (!selection || selection.isCollapsed) {
			return; // 如果没有选择或者选择已折叠，则不执行操作
		}

		// 获取包含选择文本的最近<p>元素
		range = selection.getRangeAt(0)
		txt = range.toString()
		range.deleteContents()

		newNode = document.createElement("p");
		newNode.appendChild(document.createTextNode(txt));
		range.insertNode(newNode);
	}
</script>`
}
